<script lang="renderjs" module="mapModule">
import { nextTick } from 'vue';
import { elRectification } from '@/utils/autofit.utils';

export default {
  data() {
    return {
      center: [113.078364, 27.813875]
    };
  },
  mounted() {
    this.loadMapSDK();
  },
  unmounted() {
    this.map && this.map.destroy();
  },
  methods: {
    loadMapSDK() {
      const url = 'https://webapi.amap.com/loader.js';
      const script = document.createElement('script');
      script.src = url;
      script.type = 'text/javascript';
      script.onload = () => {
        this.renderMap();
      };
      document.body.appendChild(script);
    },
    async renderMap() {
      if (!window.AMap) {
        await AMapLoader.load({
          key: 'fe355f26350f58c53f4bd609539eda73', // 申请好的Web端开发者 Key，调用 load 时必填
          version: '2.0' // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        });
      }
      this.map = new AMap.Map('map-container', {
        viewMode: '2D', // 默认使用 2D 模式
        zoom: 18, // 地图级别
        resizeEnable: true,
        center: this.center,
        mapStyle: 'amap://styles/macaron'
      });

      this.addMarker();
    },
    addMarker() {
      const icon = new AMap.Icon({
        size: new AMap.Size(40, 40), // 图标显示大小
        image: this.markerUrl,
        imageSize: new AMap.Size(40, 40) // 强制缩放图片到这个大小
      });
      const marker = new AMap.Marker({
        position: this.center,
        icon,
        offset: new AMap.Pixel(-20, -50) // 调整偏移，让图标底部对准坐标点
      });
      marker.setMap(this.map);
    },

    markerUrlChange(url) {
      this.markerUrl = url;
    },

    onScaleChange(scale) {
      nextTick(() => {
        elRectification('#map-container', scale || 1);
      });
    }
  }
};
</script>

<script>
import { buildAssetSource } from "@/utils"
import { useAppStore } from '@/store/appStore';
import {  mapState } from "pinia"

export default{
  data(){
    return {
      markerUrl: buildAssetSource('marker.png')
    }
  },
  computed: {
    ...mapState(useAppStore, ['scale'])
  },
}
</script>

<template>
  <view
    id="map-container"
    class="ignore-autofit h-full w-full"
    :scale="scale"
    :change:scale="mapModule.onScaleChange"
    :marker-url="markerUrl"
    :change:marker-url="mapModule.markerUrlChange"
  />
</template>
